import React, { useState, useEffect } from 'react';
import {
  Table,
  Card,
  Tag,
  Typography,
  Space,
  Button,
  message,
  Popconfirm,
} from 'antd';
import {
  EyeOutlined,
  DeleteOutlined,
  ClockCircleOutlined,
  CheckCircleOutlined,
  CloseCircleOutlined,
} from '@ant-design/icons';
import { Link } from 'react-router-dom';
import { getMyTorrents, deleteTorrent } from '../../api/torrent';
import { Torrent, PageResult, TORRENT_STATUS_MAP } from '../../types';
import { formatBytes, formatDateTime } from '../../utils/format';

const { Title, Text } = Typography;

const MyTorrents: React.FC = () => {
  const [torrents, setTorrents] = useState<Torrent[]>([]);
  const [loading, setLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 20,
    total: 0,
  });

  useEffect(() => {
    fetchMyTorrents();
  }, [pagination.current, pagination.pageSize]);

  const fetchMyTorrents = async () => {
    try {
      setLoading(true);
      const response = await getMyTorrents({
        page: pagination.current,
        size: pagination.pageSize,
      });

      if (response.code === 200) {
        setTorrents(response.data.records);
        setPagination(prev => ({
          ...prev,
          total: response.data.total,
        }));
      }
    } catch (error) {
      console.error('获取我的种子列表失败:', error);
      message.error('获取我的种子列表失败');
    } finally {
      setLoading(false);
    }
  };

  const handleDelete = async (torrentId: number) => {
    try {
      await deleteTorrent(torrentId);
      message.success('种子删除成功');
      fetchMyTorrents(); // 刷新列表
    } catch (error) {
      console.error('删除种子失败:', error);
      message.error('删除种子失败');
    }
  };

  const getStatusTag = (status: number) => {
    const statusInfo = TORRENT_STATUS_MAP[status as keyof typeof TORRENT_STATUS_MAP];
    let icon;
    switch (status) {
      case 0:
        icon = <ClockCircleOutlined />;
        break;
      case 1:
        icon = <CheckCircleOutlined />;
        break;
      case 2:
        icon = <CloseCircleOutlined />;
        break;
      default:
        icon = null;
    }
    
    return (
      <Tag color={statusInfo?.color || 'default'} icon={icon}>
        {statusInfo?.text || '未知'}
      </Tag>
    );
  };

  const getPromotionTag = (promotionStatus: number) => {
    switch (promotionStatus) {
      case 1:
        return <Tag color="green">免费</Tag>;
      case 2:
        return <Tag color="blue">2x上传</Tag>;
      case 3:
        return <Tag color="red">2x下载</Tag>;
      case 4:
        return <Tag color="purple">50%下载</Tag>;
      default:
        return null;
    }
  };

  const columns = [
    {
      title: '种子信息',
      dataIndex: 'title',
      key: 'title',
      render: (title: string, record: Torrent) => (
        <div>
          <Link to={`/torrents/${record.id}`}>
            <Text strong>{title}</Text>
          </Link>
          <div style={{ marginTop: 4 }}>
            <Space split={<span>•</span>}>
              <Tag color="blue">{record.category}</Tag>
              {record.promotionStatus !== undefined && getPromotionTag(record.promotionStatus)}
            </Space>
          </div>
          {record.rejectReason && (
            <div style={{ marginTop: 4 }}>
              <Text type="danger" style={{ fontSize: '12px' }}>
                拒绝原因: {record.rejectReason}
              </Text>
            </div>
          )}
        </div>
      ),
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: number) => getStatusTag(status),
    },
    {
      title: '大小',
      dataIndex: 'fileSize',
      key: 'fileSize',
      width: 100,
      render: (size: number) => formatBytes(size || 0),
    },
    {
      title: '做种/下载',
      key: 'peers',
      width: 120,
      render: (record: Torrent) => (
        <Space direction="vertical" size="small">
          <Text type="success">↑ {record.seeders}</Text>
          <Text type="warning">↓ {record.leechers}</Text>
        </Space>
      ),
    },
    {
      title: '完成',
      dataIndex: 'finished',
      key: 'finished',
      width: 80,
      render: (finished: number, record: Torrent) => (
        <Text>{finished || record.completedCount || 0}</Text>
      ),
    },
    {
      title: '上传时间',
      dataIndex: 'createdTime',
      key: 'createdTime',
      width: 150,
      render: (time: string, record: Torrent) => 
        formatDateTime(time || record.uploadedAt || ''),
    },
    {
      title: '操作',
      key: 'action',
      width: 120,
      render: (record: Torrent) => (
        <Space>
          <Link to={`/torrents/${record.id}`}>
            <Button
              type="primary"
              size="small"
              icon={<EyeOutlined />}
            >
              查看
            </Button>
          </Link>
          <Popconfirm
            title="确定要删除这个种子吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              size="small"
              icon={<DeleteOutlined />}
              danger
            >
              删除
            </Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  return (
    <div>
      <Card
        title={
          <Space>
            <Title level={3} style={{ margin: 0 }}>我的种子</Title>
            <Text type="secondary">({pagination.total} 个)</Text>
          </Space>
        }
        extra={
          <Space>
            <Button onClick={fetchMyTorrents}>刷新</Button>
            <Link to="/upload">
              <Button type="primary">上传种子</Button>
            </Link>
          </Space>
        }
      >
        <Table
          columns={columns}
          dataSource={torrents}
          rowKey="id"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) => 
              `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
            onChange: (page, pageSize) => {
              setPagination(prev => ({
                ...prev,
                current: page,
                pageSize: pageSize || 20,
              }));
            },
          }}
        />
      </Card>
    </div>
  );
};

export default MyTorrents; 